// pages/business/sweepcode/sweepcode.js
var shihan = require('../../../common/fetch');
var config = require('../../../common/config');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    code_list: [],
    show_blank: false,
    box_code: '', //盒码
    qrcode_track: '',
    shift_mobile: '',
    platform: false,
    personal: false,
    currentType: '',
    mobile_flag: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {//
    var that = this, title = '';
    if (options.index == 1) { //扫码发货
      title = '扫码发货';
      that.setData({
        word: '发货',
        currentType: options.type || '',
        order_id: options.orderid
      })
    } else if (options.index == 2) { //扫码收货
      title = '扫码收货';
      that.setData({
        word: '收货',
        currentType: options.type || '',
        order_id: options.orderid
      })
    } else if (options.index == 3) { //产品追踪
      title = '产品追踪';
    } else if (options.index == 4) { //申请转移
      title = '申请转移';
    } else if (options.index == 5) {//导出报表
      title = '导出报表';
      that.setData({
        report_id: options.id,
        report_name: options.name,
        start_date: options.sdate,
        end_date: options.ydate,
      })
    }
    that.setData({
      currentIndex: options.index
    })
    // for(var i=1;i<=50;i++){
    //   var str = i;
    //   if (i<=9) {
    //     str = '0' + i; 
    //   }
    //   that.setData({
    //     code_list: that.data.code_list.concat('S-9G9GEE7C-' + str)
    //   })
    // }
    wx.setNavigationBarTitle({
      title: title,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    if (that.data.currentIndex == 4) { //申请转移  agent_shift_detail
      shihan.sendRequest(config.agent_shift_detail, 'POST', {})
        .then(function(response) {
          if (response.data.code == 0) {
            that.setData({
              shift_detail: response.data.data
            })
          } else {
            shihan.showToast.call(that, response.data.msg);
          }
        }, function(error) {
          console.log(error);
        });
    }
  },
  //箱码(X-中间8位随机数字+字母）
  //盒码（H-中间8位随机数字+字母）
  fillCode: function(e) { //人工输入条形码
    this.checkCode(e.detail.value);
  },
  sanCode: function() { //相机识别条形码
    var that = this;
    wx.scanCode({ // 只允许从相机扫码
      onlyFromCamera: true,
      success: (res) => { //res.result == 箱码X-21de5432  盒码H-21de5432  
        // if (res.result.indexOf('http') >= 0) {}
        that.checkCode(res.result);
      }
    })
  },
  checkInput: function(e) {
    this.setData({
      box_code: e.detail.value
    })
  },
  deleteInput: function() {
    this.setData({
      box_code: ''
    })
  },
  checkCode: function(code) {
    var that = this;
    if (that.data.currentIndex == 3) { //产品追踪，只能扫盒码
      if (!(/^(H)-([\w]{8,20})$/.test(code))) {
        shihan.showToast.call(that, '二维码错误');
        return;
      } else {
        that.setData({
          box_code: code
        })
      }
    } else if (that.data.currentIndex < 3) {
      if (!(/^(X|H)-([\w]{8,20})$/.test(code))) {
        shihan.showToast.call(that, '您输入/扫描的识别码不正确，请重新输入');
        return;
      }
      if (that.data.code_list&&that.data.code_list.indexOf(code) == -1) { //则包含该元素
        that.setData({
          box_code: '',
          code_list: that.data.code_list.concat(code)
        })
      } else {
        shihan.showToast.call(that, '您输入/扫描的识别码已存在');
      }
    }
  },
  deleteCode: function(e) {
    var that = this,
      index = e.currentTarget.dataset.index;
    that.data.code_list.splice(index, 1);
    that.setData({
      code_list: that.data.code_list
    })
    //.splice(e.currentTarget.dataset.index,1);
  },
  selectPlatform: function() { //申请转移-平台
    this.setData({
      platform: !this.data.platform,
      personal: false
    })
  },
  selectPersonal: function() { //申请转移-代理商
    this.setData({
      platform: false,
      personal: !this.data.personal
    })
  },
  inputPhone: function(e) {
    this.setData({
      shift_mobile: e.detail.value
    })
    if (String(e.detail.value).length < 11) {
      this.setData({
        mobile_flag: false
      })
    }
    if (/^1(0|1|2|3|4|5|6|7|8|9)\d{9}$/.test(e.detail.value)) {
      this.setData({
        mobile_flag: true
      })
    }
  },
  formSubmit: function(e) {
    var that = this, 
      url = '', 
      data = {}, 
      formId = e.detail.formId;
    if (that.data.currentIndex < 3) {//扫码发货  扫码收货
      if (that.data.code_list.length > 0) {
        if (that.data.currentIndex == 1) { //扫码发货
          url = that.data.currentType == 1 ? config.agent_return_qrcode_shipping : config.agent_qrcode_shipping;
        } else if (that.data.currentIndex == 2) { //扫码收货
          url = that.data.currentType == 1 ? config.agent_return_qrcode_receiver : config.agent_qrcode_receiver;
        }
        data["order_id"] = that.data.order_id;
        data["codes"] = that.data.code_list;
        shihan.sendRequest(url, 'POST', data)
          .then(function(response) {
            if (response.data.code == 0) {
              shihan.showToast.call(that, that.data.word + '成功');
              var pages = getCurrentPages();
              if (pages.length >= 2) {
                var prevPage = pages[pages.length - 2];
                prevPage.setData({
                  isfresh: true
                })
              }
              setTimeout(function() {
                wx.navigateBack()
              }, 1000)
            } else {
              shihan.showToast.call(that, response.data.msg);
            }
          }, function(error) {
            console.log(error);
          });
      }
    } else if (that.data.currentIndex == 3) { //产品追踪，只能扫盒码 agent_qrcode_track_list
      if (!(/^(H)-([\w]{8,20})$/.test(that.data.box_code))) {
        shihan.showToast.call(that, '二维码错误');
        return;
      }
      shihan.sendRequest(config.agent_qrcode_track_list, 'POST', {
        code: that.data.box_code
      })
        .then(function (response) {
          // var arr = [];
          if (response.data.code == 0) {
            // if (response.data.data.sh_list.length>0) {
            //   for (var i = 0; i < 10; i++) {
            //     for (var j = 0; j < response.data.data.sh_list.length; j++) {
            //       arr.push(response.data.data.sh_list[j]);
            //     }
            //   }
            //   response.data.data.sh_list = arr;
            // }
            that.setData({
              show_blank: true,
              qrcode_track: response.data.data
            })
            // console.log(that.data.qrcode_track)
          } else {
            shihan.showToast.call(that, response.data.msg);
          }
        }, function (error) {
          console.log(error);
        });
    } else if (that.data.currentIndex == 4) {//代理商转移提交 agent_shift_apply
      data["type"] = 1;
      if (!that.data.platform && !that.data.personal) {
        return
      }
      if (!that.data.platform) {
        data["type"] = 2;
        if (!that.data.shift_mobile || !(/^1(0|1|2|3|4|5|6|7|8|9)\d{9}$/.test(that.data.shift_mobile))) {
          return;
        }
        data["mobile"] = that.data.shift_mobile
      }
      shihan.sendRequest(config.agent_shift_apply, 'POST', data)
        .then(function (response) {
          if (response.data.code == 0) {
            that.onShow();
          } else {
            shihan.showToast.call(that, response.data.msg);
          }
        }, function (error) {
          console.log(error);
        });
    } else if (that.data.currentIndex == 5) {//导出统计报表
      if (that.data.email) {//导出报表  agent_export_agent
        if (!(/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(that.data.email))) {
          shihan.showToast.call(that, '请填写正确的邮箱地址');
          return;
        }
        data["id"] = that.data.report_id;
        data["start_date"] = that.data.start_date;
        data["end_date"] = that.data.end_date;
        data["email"] = that.data.email;
        shihan.sendRequest(config.agent_export_agent, 'POST', data)
          .then(function (response) {
            if (response.data.code == 0) {
              shihan.showToast.call(that, '邮件发送成功，请到您指定的邮箱中查看');
              setTimeout(function () {
                wx.navigateBack({})
              }, 1000)
            } else {
              shihan.showToast.call(that, response.data.msg);
            }
          }, function (error) {
            console.log(error);
          });
      }
    }
    app.submissionForm(formId, '1', '5');
  },

  getEmail: function (e) {
    this.setData({
      email: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  }
})